package com.ermao.controller;

import com.ermao.pojo.User;
import com.ermao.service.PunchService;
import com.ermao.utils.Result;
import com.ermao.utils.ResultGenerator;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;

/**
 * 用户打卡模块
 * @author Ermao
 * Date: 2021/8/31 0:56
 */
@RestController
@Log4j2
@RequestMapping("/api/v1/users/punches")
public class PunchController {

	private PunchService punchService;

	@Autowired
	public void setPunchService(PunchService punchService) {
		this.punchService = punchService;
	}

	/**
	 * 用户打卡
	 * @param userId 用户 id
	 * @return 返回结果对象
	 */
	@PostMapping("")
	public Result setBudget(@RequestParam("userId") Integer userId) {
		// 检查该用户上次打卡时间是否符合要求
		User user = punchService.getLastPunchDateAndDaysByUserId(userId);
		if (user == null) {
			return ResultGenerator.genFailResult("打卡失败，请稍后重试");
		}
		LocalDate lastPunchDate = user.getLastPunchDate();
		Integer days = user.getDays();
		LocalDate now = LocalDate.now();

		if(now.isAfter(lastPunchDate)) {
			// 打卡
			if (punchService.userPunch(userId, now, days)) {
				return ResultGenerator.genSuccessResult();
			} else {
				return ResultGenerator.genFailResult("打卡失败，请稍后重试");
			}
		} else {
			// 打卡失败，一天内不能重复打卡
			return ResultGenerator.genFailResult("打卡失败，一天内不能重复打卡");
		}
	}

	/**
	 * 查看打卡天数
	 * @param userId 用户 id
	 * @return 返回结果对象
	 */
	@GetMapping("/{userId}")
	public Result getBudget(@PathVariable("userId") Integer userId) {
		User user = new User();
		Integer days = punchService.selectUserPunchDays(userId);
		if (days != null && days >= 0) {
			user.setDays(days);
			return ResultGenerator.genSuccessResult(user);
		} else {
			return ResultGenerator.genFailResult("查询打卡天数失败");
		}
	}
}
